// @flow
import React from 'react'
import { Col, Row, Table, Icon, Spin, Select  } from 'antd'
import { connect } from 'react-redux'
import styles from './Overview.css'
import Gauge from 'components/Gauge'
import GaugeStatus from 'components/GaugeStatus'
import GaugeSpeed from 'components/GaugeSpeed'
import moment from 'moment'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import ChannelBoard from 'components/ChannelBoard'
import R from 'ramda'
const Option = Select.Option
const columns = [
  {
    title: '预警类型',
    dataIndex: 'faultName',
    key: 'faultName'
  },
  {
    title: '时间',
    dataIndex: 'waringTime',
    key: 'waringTime',
    render: text => moment.utc(text, 'YYYY-MM-DDTHH:mm:ss.SSSZ').format('YYYY-MM-DD HH:mm:ss')
  },
  {
    title: '描述',
    dataIndex: 'message',
    key: 'message'
  },
  {
    title: '状态',
    dataIndex: 'dealType',
    key: 'dealType',
    render: (text, record) => {
      if (text === 0) {
        return <span className={styles['un-resolve']}>
          <Icon type='exclamation-circle' />
          未处理
        </span>
      } else if (text === 1) {
        return <span className={styles['resolve']}>
          <Icon type='check-circle' />
          已忽略
        </span>
      } else if (text === 2) {
        return <span className={styles['resolve']}>
          <Icon type='check-circle' />
          已生成工单
        </span>
      } else if (text === 3) {
        return <span className={styles['resolve']}>
          <Icon type='check-circle' />
          不显示
        </span>
      } else if (text === 4) {
        return <span className={styles['resolve']}>
          <Icon type='check-circle' />
          已短信通知
        </span>
      } else if (text === 5) {
        return <span className={styles['resolve']}>
          <Icon type='check-circle' />
          已邮件通知
        </span>
      }
    }
  }
]

type Props = {
  deviceData: Object,
  history: Object,
  userId: string
}

type States = {
  device: Object,
  vars: Array<Object>,
  mainIndicts: Array<Object>, // 核心指标（设置的核心指标）
  mainIndictNew: Object, // 改版后的最新指标显示
  faultList: Array<Object>,
  deviceStatus: Array<Object>,
  tableLoading: boolean,
  loading: boolean,
  panelYear: string, // 启停机年份
  boardZoon: boolean // 数据一览缩放
}
class Overview extends React.Component {
  props: Props
  state: States
  getDevice: Function
  interval: number
  timeOut: number
  filterData: Function
  goToCondition: Function
  goToService: Function
  getStatus: Function
  changePanelYear: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      device: {},
      vars: [],
      mainIndicts: [],
      mainIndictNew: {},
      faultList: [],
      deviceStatus: [],
      tableLoading: false,
      loading: true,
      panelYear: '2018',
      boardZoon: false
    }
    this.filterData = this.filterData.bind(this)
    this.goToCondition = this.goToCondition.bind(this)
    this.goToService = this.goToService.bind(this)
    this.getStatus = this.getStatus.bind(this)
    this.changePanelYear = this.changePanelYear.bind(this)
  }
  componentDidMount () {
    const { deviceData } = this.props
    this.getTasks(deviceData.deviceNo)
    this.getStatus()
  }

  componentWillUnmount () {
    clearInterval(this.interval)
  }
  getStatus () {
    universalFetch(`${__SERVICE_API__}sys/dicts?type=deviceStatus`)
    .then((res) => res.json())
    .then((json) => {
      if (json.code !== 200000) {
        throw new Error(JSON.stringify({ code: json.code, message: json.message }))
      }
      this.setState({
        deviceStatus: json.result
      })
    })
    .catch((error) => {
      handleFetchError(error)
      console.error(error)
    })
  }
  getTasks (deviceNo) {
    this.setState({
      tableLoading: true
    })
    universalFetch(`${__SERVICE_API__}analysis/warings?deviceNo=${deviceNo}&status=mq&owner=${this.props.userId}`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          tableLoading: false,
          faultList: json.result.map((d, i) => {
            d['key'] = i
            d['waringTime'] = moment.utc(d.waringTime).format('YYYY-MM-DD HH:mm:ss')
            return d
          })
        })
      })
      .catch((error) => {
        this.setState({
          tableLoading: false,
          faultList: []
        })
        handleFetchError(error)
        console.error(error)
      })
  }

  filterData (result, loading) {
    this.setState({
      // mainIndicts: result,
      mainIndictNew: result,
      loading: loading
    })
  }

  goToCondition (item, channel) {
    const { deviceData, history } = this.props
    const location = {
      pathname: `/device-file/${deviceData.id}/condition`,
      state: {
        defaultActiveKey: 'dynamicTab',
        dynamicIndicator: item.sensorNameEn + '___' + item.kmxVariableNameEn,
        defaultChannel: channel
      }
    }
    history.push(location)
  }
  goToService () {
    const { deviceData, history } = this.props
    history.push(`/device-file/${deviceData.id}/Service`)
  }
  changePanelYear (value) {
    this.setState({
      panelYear: value
    })
  }
  boardZoon = () => {
    const { boardZoon } = this.state
    this.setState({
      boardZoon: !boardZoon
    })
  }
  render () {
    const { deviceData } = this.props
    const { mainIndictNew, faultList, tableLoading, deviceStatus, boardZoon } = this.state
    // const component = this
    const goToCondition = this.goToCondition
    // const tdevice = deviceData.tdevice || ''
    const imageUrl = deviceData.imageUrl || '/noimg.jpg'
    let statusValue = '' // 设备状态
    let susbNUm = 0 // 启停机次数
    let speedList = [] // 转速
    const len = deviceStatus.length
    deviceStatus.map((d, i) => {
      if (mainIndictNew.status && d.value === mainIndictNew.status) {
        statusValue = 1 / len * 100 * (i + 1) - 1 / len * 50
      }
    })
    if (mainIndictNew.hasOwnProperty('susbNUm')) {
      susbNUm = mainIndictNew.susbNUm
    }
    if (mainIndictNew.hasOwnProperty('speedList')) {
      speedList = mainIndictNew.speedList
    }
    return (
      <div className={styles['main']}>
        <div className={styles['over-content']}>
          <Row>
            <Col span='10'>
              {
                boardZoon
                ? false
                : <div className={styles['err-info']}
                  style={{ height:300, marginBottom: 20, marginLeft: 0, padding: 0 }}>
                  <img className={styles['deviceImg']} src={imageUrl} />
                </div>
              }
              <div className={boardZoon ? styles['data-overview2'] : styles['data-overview']}>
                {
                  boardZoon
                  ? <Icon title='缩小' onClick={this.boardZoon} className={styles['arrows-alt']} type='shrink' />
                  : <Icon title='放大' onClick={this.boardZoon} className={styles['arrows-alt']} type='arrows-alt' />
                }
                <ChannelBoard {...{
                  filterData: this.filterData,
                  goToCondition,
                  deviceData,
                  panelYear: this.state.panelYear
                }} />
              </div>
            </Col>
            <Col span='14'>
              <div className={styles['err-info']} style={{ height:300, marginBottom: 20 }}>
                <div className={styles['over-top-title']}>
                  <i className='fa fa-key' aria-hidden='true' />
                  <span>核心指标</span>
                </div>
                <Spin spinning={false}>
                  <div className={styles['over-top-gauge']}>
                    <Row>
                      <Col span='8'>
                        <div className={styles['over-gauge-title2']}>
                          设备状态
                        </div>
                        <div className={styles['over-gauge']}>
                          <GaugeStatus {...{
                            deviceStatus: deviceStatus,
                            color: '#abc966',
                            valueColor: '#666',
                            min: 0,
                            max: 100,
                            name: '设备状态',
                            unit: mainIndictNew.status ? mainIndictNew.status : '',
                            value: statusValue
                          }} />
                        </div>
                      </Col>
                      <Col span='8'>
                        <div className={styles['over-gauge-title2']}>
                          转速
                        </div>
                        <div className={styles['over-gauge']}>
                          <GaugeSpeed {...{
                            color: '#91c7ae',
                            valueColor: '#666',
                            min: 0,
                            max: 15000,
                            name: '转速',
                            speedList: speedList
                          }} />
                        </div>
                      </Col>
                      <Col span='8'>
                        <div className={styles['over-gauge-title2']}>
                          启停机次数
                          <Select
                            value={this.state.panelYear}
                            style={{ width: 60, marginLeft:5 }}
                            onChange={this.changePanelYear}>
                            <Option value='2018'>2018</Option>
                            <Option value='2017'>2017</Option>
                            <Option value='2016'>2016</Option>
                            <Option value='2015'>2015</Option>
                          </Select>
                        </div>
                        <div className={styles['over-gauge']}>
                          <Gauge {...{
                            color: '#abc966',
                            valueColor: '#666',
                            min: 0,
                            max: 100,
                            name: '启停机次数',
                            unit: '',
                            value: susbNUm
                          }} />
                        </div>
                      </Col>
                    </Row>
                  </div>
                </Spin>
              </div>
              <div className={styles['err-info']}>
                <header className={styles['err-info-header']}>
                  <i className='fa fa-info-circle' aria-hidden='true' />
                  <span>报警信息</span>
                  <a onClick={this.goToService} className={styles['more-err']}>
                    更多
                  </a>
                </header>
                <div className={styles['err-info-table']}>
                  <Spin spinning={tableLoading} style={{ height: 180 }}>
                    <Table {...{
                      columns,
                      dataSource: faultList,
                      pagination: false
                    }} />
                  </Spin>
                </div>
              </div>
            </Col>
          </Row>
        </div>
      </div>
    )
  }
}

const mapStatesToProps = (state) => {
  const { deviceCard } = state
  return {
    groupId: deviceCard.groupId,
    deviceData: deviceCard.deviceData,
    userId: state.user.userId
  }
}
export default connect(mapStatesToProps, {})(Overview)
